var express = require('express');
var path = require('path');
var cors = require('cors');
var expressJwt = require('express-jwt');
var { getToken } = require('./util/token')
var router = require('./router');

var app = express();

// 配置跨域 cors
app.use(cors());

//接受特定来源
/* app.use(cors({
  origin: 'http://localhost:5173'
})) */

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

// 配置静态资源访问 - 将这些配置提前，确保在token验证前就可以访问
app.use('/public', express.static(path.join(__dirname, 'public')));
app.use('/uploads', express.static(path.join(__dirname, 'public/uploads')));
// 直接访问avatars文件夹
app.use('/uploads/avatars', express.static(path.join(__dirname, 'public/uploads/avatars')));

// 验证token是否过期以及不需要验证的路由(express-jwt)
app.use(expressJwt.expressjwt({
  secret: 'bookshop_token', //签名
  algorithms: ['HS256']    //签名算法,HS256是一种默认加密算法
}).unless({
  path: [
    '/boodsList', '/category', '/login', '/register', '/hotBook', 
    '/booksSubject', '/shopcartList', '/sections', '/hotBookBySection', 
    '/editorRecommend', '/booksList', '/searchBooks', '/randomBooks', 
    '/admin/users', '/admin/login', '/admin/dashboard/statistics', 
    '/admin/dashboard/hotBooks', '/admin/dashboard/activities', '/admin/books', 
    /\/admin\/users(\/.*)?/, /\/booksDetails(\/.*)?/, /\/booksByCategory(\/.*)?/, /\/admin\/books(\/.*)?/,
    // 添加静态资源路径到白名单
    /^\/public\/.*/,
    /^\/uploads\/.*/
  ] // 不需要验证的路由
}))

//验证token真假，解析token获取用户信息
app.use((req, res, next) => {
  // 检查是否是静态资源请求
  if (req.path.startsWith('/public/') || req.path.startsWith('/uploads/')) {
    return next();
  }

  // 检查是否是需要验证token的路径
  const isProtectedPath = !(['/boodsList', '/category', '/login', '/register', '/hotBook', '/booksSubject', '/shopcartList', '/sections', '/hotBookBySection', '/editorRecommend', '/booksList', '/searchBooks', '/randomBooks', '/admin/users', '/admin/login', '/admin/dashboard/statistics', '/admin/dashboard/hotBooks', '/admin/dashboard/activities', '/admin/books'].includes(req.path) || 
                          /^\/booksDetails\//.test(req.path) || 
                          /^\/booksByCategory\//.test(req.path) ||
                          /^\/admin\/users\//.test(req.path) ||
                          /^\/admin\/books\//.test(req.path));
  
  let token = req.headers['authorization']
  if (token == undefined) {
    // 如果是受保护的路径但没有token，返回401
    if (isProtectedPath) {
      return res.send({ code: 401, message: '请先登录' });
    }
    return next()
  } else {
    getToken(token).then((data) => { //data就是解析后的token （就是存储的u_id和username） 
      req.data = data  //给req追加data属性，属性值为存储用户登录信息
      console.log(req.data)
      return next()
    })
      .catch(err => {
        console.log('token验证错误:' + err.message)
        // 如果是受保护的路径但token无效，返回401
        if (isProtectedPath) {
          return res.send({ code: 401, message: 'token无效，请重新登录' });
        }
        return next()
      })
  }
})

//token失效返回信息
app.use((err, req, res, next) => {
  if (err.status == 401) {
    console.log(err.message)
    console.log(123132)
    res.send({ code: 401, message: 'token失效' })
  } else {
    console.log(123)
    next()
  }
})

// 路由
app.use(router);

// token错误处理
app.use((err, req, res, next) => {
  if (err.name === 'UnauthorizedError') {
    res.status(401).send({ code: 401, message: '无效的token', data: null });
  } else {
    next(err);
  }
});

module.exports = app;